package GTGExpession;
import java.util.*;

/**
 * 
 */

/**
 * Class for keeping expression as a list of OR statements
 * ENG: sum element contains products
 * PL:  skladnikami sum sa iloczyny
 * @author Tomasz Werszko
 * @author Rafal Magda
 */
public class GTGOr implements Comparator<GTGOr>{
	/*public class GTGOrStringComparator implements Comparator<GTGOr>{
		public int compare(GTGOr or1, GTGOr or2){
			if(or1 == or2){
				return 0;
			}
			if(or1 == null){
				return -1;
			}
			if(or2 == null){
				return 1;
			}
			if(or1.ands.size() == 0 && or2.ands.size() == 0){
				return 0;
			}else if(or1.ands.size() == 0){
				return -1;
			}else if(or2.ands.size() == 0){
				return 1;
			}else{
				return or1.ands.get(0)
			}
		}
		
	}*/
	public ArrayList<GTGAnd> ands = new ArrayList<GTGAnd>();
	
	public GTGOr(String text){
		ands = new ArrayList<GTGAnd>();
		
		int orBegin=0, orEnd=0;
		boolean end=false;
		while(end==false){
			orEnd = text.indexOf("+",orBegin);
			if(orEnd<0){
				orEnd=text.length();
				end=true;
			}
			String s_or = text.substring(orBegin, orEnd);
			ands.add(new GTGAnd(s_or));
			orBegin=orEnd+1;
		}
	}
	
	public GTGOr() {
		ands = new ArrayList<GTGAnd>();
	}
	
	/**
	 * Returns string representation of this object
	 */
	public String toString(){
		String result = new String();
		
		Iterator<GTGAnd> iterator = this.ands.iterator();
		while(iterator.hasNext()){
			GTGAnd and = iterator.next();
			String string = and.toString();
			if(result.length() > 0 && string.length() > 0){
				result += "+";
			}
			result += string;
		}
		return result;
	}

	/**
	 * Compares two {@link GTGOr} elements.
	 * (needed in sort method) 
	 * @return -1 - if first element should be before second
	 * <br>
	 * 0 - if elements are equal
	 * <br>
	 * 1 - if first element should be after second element (elements should swap) 
	 */
	public int compare(GTGOr or1, GTGOr or2){
		Iterator<GTGAnd> iteratorAnd1 = or1.ands.iterator();
		Iterator<GTGAnd> iteratorAnd2 = or2.ands.iterator();
		
		// min1,min2 - numbers of variables in products 
		int min1=-1;
		while(iteratorAnd1.hasNext()){
			ArrayList<String> variables1 = iteratorAnd1.next().variables;
			if(min1==-1 || min1<variables1.size()){
				min1=variables1.size();
			}
		}

		int min2=-1;
		while(iteratorAnd2.hasNext()){
			ArrayList<String> variables2 = iteratorAnd2.next().variables;
			if(min2==-1 || min2<variables2.size()){
				min2=variables2.size();
			}
		}			

		if(min1<min2){
			return -1;
		}else if(min1>min2){
			return 1;
		}else{
			// terms1,terms2 - number of terms in sums
			int terms1 = or1.ands.size();
			int terms2 = or2.ands.size();
			if(terms1>terms2){
				return -1;
			}else if(terms1<terms2){
				return 1;
			}else
				return 0;
		}
	}	
}
